import Taro from '@tarojs/taro'
import { uploadImg } from '@api/api'
import { IMG_ADMIN, TABBAR_PATH } from '@config'
export function getUserInfo() {
  let userInfo = Taro.getStorageSync("userInfo") ? JSON.parse(Taro.getStorageSync("userInfo")) : {}

  return userInfo
}


// 精确判断数据类型
export function queryDataType (data, type) {
  let queryType = Object.prototype.toString.call(data)
  if ( queryType === `[object ${type}]` ) {
    return true
  } else {
    console.warn('传入参数与检测类型不同')
    return false
  }
}

// 获取小程序DOM的client值
export function getClientRect (ctx, dom) {
  return new Promise((resolve, reject) => {
    Taro.createSelectorQuery().in(ctx.$scope)
    .select(dom)
    .boundingClientRect(res => {
      if (res) {
        resolve(res)
      } else {
        reject(false)
      }
    })
    .exec();
  })
}

// 转换rpx为px
export function convertRPXToPx(rpx) {
  const { windowWidth } = Taro.getSystemInfoSync();
  let px = rpx * windowWidth / 750;
  return px;
}

// 转换px为rpx
export function convertPXToRpx(px) {
  const { windowWidth } = Taro.getSystemInfoSync()
  let rpx = px / (windowWidth / 750)
  return rpx;
}

// 返回年月日时间格式
export function formatTime(t) {
  const d = new Date(t);
  return `${d.getFullYear()}年${d.getMonth() + 1 >= 10? d.getMonth() + 1 : '0' + (d.getMonth() + 1)}月${d.getDate() >= 10? d.getDate() : '0' + d.getDate()}日`
}

/**
 * 格式化日期
 * @method formatDate
 * @param {Date} date 日期
 * @param {String} formation 日期格式
 * @return {String} 格式化后的日期字符串
 */
export function formatDate(date=0, formation = 'YYYY-MM-DD hh:mm:ss') {
  if (!date) {
    return '';
  }

  if (typeof date !== 'object') {
    date = new Date(date)
  }

  date = new Date(date);

  
	let values = {
		Y: date.getFullYear(),
		M: date.getMonth() + 1,
		D: date.getDate(),
		h: date.getHours(),
		m: date.getMinutes(),
		s: date.getSeconds()
	};

	return formation.replace(/Y+|M+|D+|h+|m+|s+/g, function(match) {
		let result = values[match[0]];
		if (match.length > 1 && result.toString().length !== match.length) {
			result = ((new Array(match.length)).join('0') + result).slice(-match.length);
		}
		return result;
	});
}

/**
 * 将http转为https
 * @param {String}} rawUrl 图片资源url
 * @returns { string }
 */
export function mapHttpToHttps(rawUrl) {
  if (rawUrl.indexOf(':') < 0) {
    return rawUrl;
  }
  const urlComponent = rawUrl.split(':');
  if (urlComponent.length === 2) {
    if (urlComponent[0] === 'http') {
      urlComponent[0] = 'https';
      return `${urlComponent[0]}:${urlComponent[1]}`;
    }
  }
  return rawUrl;
}


// 加密手机号显示
export function encryptMobile ( tel ) {
  let str = `${tel}`
  let str1 = str.substr(0, 4)
  let str2 = str.substr(7, 11)
  return str1 + '****' + str2
}

export function deepClone(obj) {
  var o;
  // 如果  他是对象object的话  , 因为null,object,array  也是'object';
  if (typeof obj === 'object') {

    // 如果  他是空的话
    if (obj === null) {
      o = null;
    }
    else {

      // 如果  他是数组arr的话
      if (obj instanceof Array) {
        o = [];
        for (var i = 0, len = obj.length; i < len; i++) {
          o.push(deepClone(obj[i]));
        }
      }
      // 如果  他是对象object的话
      else {
        o = {};
        for (var j in obj) {
          o[j] = deepClone(obj[j]);
        }
      }

    }
  }
  else {
    o = obj;
  }
  return o;
};

// 是否携带地址链接
export function isUrl(url) {
  let reg = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/
  return reg.test(url)
}

export function changePrice(price) {
  const [int, dec] = price.toString().includes('.') ? price.toString().split('.') : [price]
  return {
    int,
    dec
  }
}

export function uploadImgs(count) {
  return new Promise((resolve, reject) => {
    Taro.chooseImage({
      sourceType: ['album', 'camera'],
      count
    }).then(({ tempFilePaths }) => {
      Promise.all(tempFilePaths.map(item => {
        return new Promise(imgsResolve => {
          uploadImg(item).then(({ url }) => {
            imgsResolve(url)
          })
        })
      })).then(urls => {
        resolve(urls)
      })
    })
  })
}

export function goPage(url, redurect = false) {
  if (TABBAR_PATH.includes(url)) {
    Taro.switchTab({
      url
    })
  } else {
    if (redurect) {
      Taro.redirectTo({
        url
      })
    } else {
      Taro.navigateTo({
        url
      })
    }
  }
}

export function getDate(timeStamp = Date.now(), days = 0) {
  var date = new Date(timeStamp)
  date.setDate(date.getDate() + days)
  var newDate = date.getFullYear() + '.' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '.' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
  return newDate
}

export function previewImg(urls, index = 0) {
  const url = urls[index]
  Taro.previewImage({
    urls,
    current: url
  })
}

export function isEmail(str) {
  return /.+@.+\..+/.test(str)
}
